﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using Microsoft.Win32;
using MyKnights.Entity;
using MyKnights.UI;

namespace MyKnights
{
    public class CenterHandler
    {
        public UserData UserData { get; set; }

        public Knights Knights { get; set; }

        public Profile CurrentProfile { get; set; }

        public ChangeLogManager ChangeLogManager { get; set; }

        private IMainWindow _mainWindow;

        private bool _initialized;

        public bool Initialized => _initialized;

        public void Initialize(IMainWindow mainWindow)
        {
            if (_initialized) return;
            _mainWindow = mainWindow;
            UserData = UserData.Initialize();
            _mainWindow.ApplyAppStatus(UserData.AppStatus);

            Knights = Knights.Initialize();
            ChangeLogManager = ChangeLogManager.Initialize();
            LoadProfile();

            _initialized = true;
        }

        public void LoadProfile()
        {
            CurrentProfile = UserData.GetSelectedProfile();
            _mainWindow.InitProfile(UserData);
        }

        public void UpdateKnightTopic(Knight knight, Topic fromTopic, Topic toTopic)
        {
            int index = toTopic.Index;
            string baseKey = knight.BaseKey;

            if (Elsie.Key.Equals(baseKey))
            {
                CurrentProfile.Elsie = index;
            }
            else if (Eirlys.Key.Equals(baseKey))
            {
                CurrentProfile.Eirlys = index;
            }
            else if (Dai.Key.Equals(baseKey))
            {
                CurrentProfile.Dai = index;
            }
            else if (Kaour.Key.Equals(baseKey))
            {
                CurrentProfile.Kaour = index;
            }

            UserData.SaveToFile();

            if (fromTopic == null) fromTopic = toTopic;
            var log = new ChangeLog
            {
                ChangeTime = DateTime.Now,
                ToIndex = toTopic.Index,
                ToTopic = toTopic.Name,
                FromIndex = fromTopic.Index,
                FromTopic = fromTopic.Name,
                ProfileName = CurrentProfile.Name,
                KnightName = knight.Name
            };

            ChangeLogManager.Add(log);
            _mainWindow.RefreshLogs();
        }

        public void ChangeProfile(Profile item)
        {
            foreach (var topic in UserData.Profiles)
            {
                topic.Selected = topic.Name.Equals(item.Name);
            }
            CurrentProfile = UserData.GetSelectedProfile();

            UserData.SaveToFile();
            Knights.Elsie.CurrentTopic = CurrentProfile.Elsie;
            Knights.Eirlys.CurrentTopic = CurrentProfile.Eirlys;
            Knights.Dai.CurrentTopic = CurrentProfile.Dai;
            Knights.Kaour.CurrentTopic = CurrentProfile.Kaour;
            _mainWindow.LoadTopics(Knights);
            _mainWindow.LoadKnightVisibility(CurrentProfile.KnightVisibility);
        }

        public void UpdateProfile(ProfileEditWindow.Operation operation, Profile storedProfile)
        {
            if (operation == ProfileEditWindow.Operation.Delete)
            {
                UserData.DeleteProfile(CurrentProfile);
                LoadProfile();
                return;
            }

            if (storedProfile == null || string.IsNullOrWhiteSpace(storedProfile.Name))
            {
                return;
            }

            if (operation == ProfileEditWindow.Operation.Edit)
            {
                CurrentProfile.Name = storedProfile.Name;
                CurrentProfile.KnightVisibility.Elsie = storedProfile.KnightVisibility.Elsie;
                CurrentProfile.KnightVisibility.Eirlys = storedProfile.KnightVisibility.Eirlys;
                CurrentProfile.KnightVisibility.Kaour = storedProfile.KnightVisibility.Kaour;
                CurrentProfile.KnightVisibility.Dai = storedProfile.KnightVisibility.Dai;
                UserData.SaveToFile();
                LoadProfile();
            }
            else if (operation == ProfileEditWindow.Operation.Add)
            {
                UserData.AddProfile(storedProfile);
                LoadProfile();
            }
        }

        public void ClearLog()
        {
            ChangeLogManager?.Clear();
            _mainWindow.RefreshLogs();
        }

        public bool SaveLogToFile()
        {
            SaveFileDialog sf = new SaveFileDialog();
            //设置文件保存类型
            sf.Filter = "txt文件|*.txt|所有文件|*.*";
            //如果用户没有输入扩展名，自动追加后缀
            sf.AddExtension = true;
            sf.Title = "导出文件";
            if (sf.ShowDialog() == true)
            {
                FileStream fs = new FileStream(sf.FileName, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                foreach (var log in ChangeLogManager.Logs)
                {
                    sw.WriteLine(log.DisplayText);
                    sw.Flush();
                }
                sw.Close();
                fs.Close();
                return true;
            }
            return false;
        }

        public void OnAppClose()
        {
            if (UserData == null) return;
            UserData.AppStatus.LastCloseTime = DateTime.Now;
            UserData.SaveToFile();
        }
    }
}
